﻿using Windows.Storage.Pickers;
using WinRT.Interop;

namespace DimensionsHelper.Client.WinUi.Services;

public class FilePickerService : IFilePikerService
{
    public async Task<IReadOnlyList<string>> PickMultipleFilesAsync(params string[] typeFilters) =>
        (await CreateFileOpenPicker(typeFilters).PickMultipleFilesAsync())?.Select(f => f.Path).ToList() ?? [];


    public async Task<string?> PickSingleFileAsync(params string[] typeFilters) =>
        (await CreateFileOpenPicker(typeFilters).PickSingleFileAsync())?.Path;


    public async Task<string?> SaveFileAsync(params string[] typeFilters)
    {
        FileSavePicker? picker = new();
        InitializeWithWindow.Initialize(picker, WindowNative.GetWindowHandle(App.MainWindow));
        foreach (string? filter in typeFilters)
        {
            string[] items = filter.Split('|');

            if (items.Length != 2)
            {
                continue;
            }

            List<string> extensions = [];

            foreach (string item in items[1].Split(';'))
            {
                string ext = item;
                int dotIndex = ext.IndexOf('.');
                if (dotIndex == -1)
                {
                    continue;
                }

                if (dotIndex != 0)
                {
                    ext = ext[dotIndex..];
                }

                extensions.Add(ext);
            }

            picker.FileTypeChoices.Add(items[0], extensions);
        }

        return (await picker.PickSaveFileAsync())?.Path;
    }

    private static FileOpenPicker CreateFileOpenPicker(params string[] typeFilters)
    {
        FileOpenPicker? picker = new();
        IntPtr hwnd = WindowNative.GetWindowHandle(App.MainWindow);
        InitializeWithWindow.Initialize(picker, hwnd);
        picker.ViewMode = PickerViewMode.Thumbnail;

        foreach (string typeFilter in typeFilters)
        {
            string[] items = typeFilter.Split('|');
            foreach (string item in items[^1].Split(';'))
            {
                string typeExtension = item;
                int dotIndex = typeExtension.IndexOf('.');

                if (dotIndex == -1)
                {
                    continue;
                }

                if (dotIndex != 0)
                {
                    typeExtension = typeExtension[dotIndex..];
                }

                picker.FileTypeFilter.Add(typeExtension);
            }
        }

        return picker;
    }
}